package com.example.clothingmanager.service;

import com.example.clothingmanager.bean.Clothes;
import com.example.clothingmanager.bean.Instock;
import com.example.clothingmanager.dao.InstockDao;
import com.example.clothingmanager.dao.InstockMapper;
import com.example.clothingmanager.utils.InstockQuery;
import com.example.clothingmanager.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/5/9 15:55
 */
@Service
public class InstockService {
    @Autowired
    InstockDao InstockDao;
    @Autowired
    ClothesService clothesService;
    @Autowired
    InstockMapper instockMapper;

    public Result list(int depotid, int page, int size, InstockQuery query){
        if(page<1){
            page = 1;
        }
        //mybatis分页起始为1
        PageHelper.startPage(page, size);
        List<Instock> all = instockMapper.list(query, depotid);
        PageInfo<Instock> list = new PageInfo<>(all);
        return Result.success(list);
    }

    public Result add(Instock instock){
        Optional<Instock> optional = InstockDao.findById(instock.getIsitem());
        if(!optional.isPresent()){
            instock.setSum(instock.getNum()*instock.getPrice());
            return Result.success(InstockDao.saveAndFlush(instock));
        }
        return Result.fail("入库ID已存在，添加失败");
    }

    public Result update(Instock instock){
        Optional<Instock> optional = InstockDao.findById(instock.getIsitem());
        if(optional.isPresent()){
            return Result.success(InstockDao.saveAndFlush(instock));
        }
        return Result.fail("仓库ID不存在，更新失败");
    }

    public Result delete(String isitem){
        Optional<Instock> optional = InstockDao.findById(isitem);
        if(optional.isPresent()){
            InstockDao.deleteById(isitem);
            return Result.success();
        }
        return Result.fail("仓库ID不存在，删除失败");
    }

    public Result get(String isitem){
        Optional<Instock> optional = InstockDao.findById(isitem);
        if(optional.isPresent()){
            return Result.success(optional.get());
        }
        return Result.fail("仓库ID不存在，获取数据失败");
    }

    public Result getNames(){
        List<String> stocknames = InstockDao.getStocknames();
        if(null!=stocknames){
            return Result.success(stocknames);
        }
        return Result.fail("获取仓库名称列表失败");
    }
}
